#if ANDROID
using Android;
using Android.App;
using Android.Content;
using Android.OS;
using AndroidX.Core.App;
using RadioTimer.Services;

namespace RadioTimer.Platforms.Android
{
    [Service(ForegroundServiceType = global::Android.Content.PM.ForegroundService.TypeDataSync)]
    public class ForegroundService : Service
    {
        private const int ServiceNotificationId = 1001;
        private const string ChannelId = "RadioTimerChannel";
        private const string ChannelName = "语音报时服务";
        private bool _isServiceRunning = false;

        private ITimeChimeService? _timeChimeService;

        public override void OnCreate()
        {
            base.OnCreate();
            CreateNotificationChannel();
        }

        public override StartCommandResult OnStartCommand(Intent? intent, StartCommandFlags flags, int startId)
        {
            try
            {
                if (!_isServiceRunning)
                {
                    _isServiceRunning = true;

                    // 获取服务实例
                    _timeChimeService = MauiApplication.Current?.Services?.GetService<ITimeChimeService>();

                    // 创建前台通知
                    var notification = CreateNotification();
                    StartForeground(ServiceNotificationId, notification);

                    // 启动报时服务
                    Task.Run(async () =>
                    {
                        try
                        {
                            await _timeChimeService?.StartServiceAsync();
                        }
                        catch (Exception ex)
                        {
                            Services.DebugLogger.WriteError($"Error starting chime service: {ex.Message}");
                        }
                    });

                    Services.DebugLogger.WriteLine("ForegroundService started successfully");
                }

                return StartCommandResult.Sticky;
            }
            catch (Exception ex)
            {
                Services.DebugLogger.WriteError($"Error in OnStartCommand: {ex.Message}");
                return StartCommandResult.NotSticky;
            }
        }

        public override void OnDestroy()
        {
            try
            {
                _isServiceRunning = false;

                // 停止报时服务
                Task.Run(async () =>
                {
                    try
                    {
                        await _timeChimeService?.StopServiceAsync();
                    }
                    catch (Exception ex)
                    {
                        Services.DebugLogger.WriteError($"Error stopping chime service: {ex.Message}");
                    }
                });

                Services.DebugLogger.WriteLine("ForegroundService destroyed");
            }
            catch (Exception ex)
            {
                Services.DebugLogger.WriteError($"Error in OnDestroy: {ex.Message}");
            }

            base.OnDestroy();
        }

        public override IBinder? OnBind(Intent? intent)
        {
            return null;
        }

        private void CreateNotificationChannel()
        {
            try
            {
                if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                {
                    var channel = new NotificationChannel(ChannelId, ChannelName, NotificationImportance.Low)
                    {
                        Description = "语音报时后台服务通知"
                    };

                    var notificationManager = GetSystemService(NotificationService) as NotificationManager;
                    notificationManager?.CreateNotificationChannel(channel);
                }
            }
            catch (Exception ex)
            {
                Services.DebugLogger.WriteError($"Error creating notification channel: {ex.Message}");
            }
        }

        private Notification CreateNotification()
        {
            try
            {
                // 创建点击通知时的Intent
                var intent = new Intent(this, typeof(MainActivity));
                intent.SetFlags(ActivityFlags.SingleTop);
                var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.UpdateCurrent | PendingIntentFlags.Immutable);

                var builder = new NotificationCompat.Builder(this, ChannelId)
                    .SetContentTitle("语音报时")
                    .SetContentText("报时服务正在后台运行")
                    .SetSmallIcon(Resource.Drawable.notification_icon_background) // 需要添加图标
                    .SetContentIntent(pendingIntent)
                    .SetOngoing(true)
                    .SetPriority(NotificationCompat.PriorityLow)
                    .SetCategory(NotificationCompat.CategoryService);

                return builder.Build();
            }
            catch (Exception ex)
            {
                Services.DebugLogger.WriteError($"Error creating notification: {ex.Message}");
                
                // 创建最简单的通知作为fallback
                var fallbackBuilder = new NotificationCompat.Builder(this, ChannelId)
                    .SetContentTitle("语音报时")
                    .SetContentText("报时服务正在运行")
                    .SetSmallIcon(global::Android.Resource.Drawable.IcDialogInfo);

                return fallbackBuilder.Build();
            }
        }
    }
}
#endif